<template>
  <div class="address-wrap">
    <van-nav-bar
      title="地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      fixed
    />
    <div class="address">
      <div v-if="addressList.length == 0">
        <div class="address_content">
          <img src="../assets/image/address.png" alt="" />
          <p>您还没有收货地址，快去添加一个吧~</p>
        </div>
        <div class="address_button">
          <van-button color="#e50055" size="large" @click="onAdd('add')"
            >添加地址</van-button
          >
        </div>
      </div>
      <div v-else>
        <van-address-list
          v-model="chosenAddressId"
          :list="addressList"
          default-tag-text="默认"
          @add="onAdd('add')"
          @edit="onEdit"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import { onBeforeMount } from "@vue/runtime-core";
import axios from "../utils/axios";
import { Toast } from "vant";
import { useRouter } from "vue-router";
export default {
  setup() {
    const router = useRouter();
    const state = reactive({
      addressList: [],
      chosenAddressId: 1,
      uid: 0,
    });
    const onClickLeft = () => history.back();
    //添加地址
    const onAdd = (e) => {
      console.log("add");
      router.push({
        path: "addAddress",
        query: { uid: state.uid, isedit: e == "edit" ? true : false },
      });
    };
    const onEdit = (item, index) => Toast("编辑地址:" + index);
    onBeforeMount(() => {
      let { uid } = JSON.parse(localStorage.getItem("userinfo"));
      state.uid = uid;
      axios
        .get("/getaddress", {
          params: {
            user_id: uid,
          },
        })
        .then((res) => {
          if (res.data.code == 1) {
            console.log(res.data.result);
            const dataList = [];
            res.data.result.map((item, index) => {
              let obj = {};
              obj.id = index + 1;
              obj.name = item.linkman;
              obj.tel = item.phone;
              obj.address = item.province + "," + item.house_number;
              dataList.push(obj);
            });
            console.log(dataList);
            state.addressList = dataList;
          } else {
            Toast("查找失败");
            return;
          }
        });
    });
    return {
      ...toRefs(state),
      onClickLeft,
      onAdd,
      onEdit,
    };
  },
};
</script>

<style lang="less" scoped>
.address-wrap {
  .address {
    margin-top: 48px;
    .address_content {
      text-align: center;
      color: #333;
      margin: 140px 0;
      img {
        margin-bottom: 60px;
      }
      p {
        font-size: 18px;
      }
    }
    .address_button {
      position: fixed;
      bottom: 0;
      right: 0;
      left: 0;
    }
  }
}
</style>
<style lang="less" scoped>
.van-address-list__bottom {
  background-color: #fff !important;
}
</style>